<!DOCTYPE html>
<script src='../resources/testharness.js'></script>
<script src='../resources/testharnessreport.js'></script>
<script src='resources/shadow-dom.js'></script>
<script src="../resources/testdriver.js"></script>
<script src="../resources/testdriver-vendor.js"></script>

<div id='host'>
  <template data-mode='open'>
    <slot></slot>
  </template>
  <div id='host2'>
    <template data-mode='open'>
      <div id='host3'>
        <template data-mode='open'>
          <canvas></canvas>
          <div id='host4'>
            <template data-mode='open'>
              <div></div>
            </template>
          </div>
        </template>
      </div>
      <div id='host5'>
        <template data-mode='open'>
          <div></div>
        </template>
      </div>
    </template>
  </div>
</div>

<script>
promise_test(async (test) => {
    document.onpointerlockerror = test.unreached_func('onpointerlockerror is not expected.');

    document.onpointerlockchange = test.step_func(() => {
        // Not interested in handling before or after exitPointerLock.
        if (document.pointerLockElement === null)
            return;

        assert_equals(document.pointerLockElement, host2, 'document.pointerLockElement should be shadow host2.');
        assert_equals(host.shadowRoot.pointerLockElement, null, 'host\'s shadowRoot.pointerLockElement should be null.');
        assert_equals(host2.shadowRoot.pointerLockElement, host3, 'host2\'s shadowRoot.pointerLockElement should be host3.');
        assert_equals(host3.shadowRoot.pointerLockElement, canvas, 'host3\'s shadowRoot.pointerLockElement should be canvas element.');
        assert_equals(host4.shadowRoot.pointerLockElement, null, 'host4\'s shadowRoot.pointerLockElement should be null.');
        assert_equals(host5.shadowRoot.pointerLockElement, null, 'host5\'s shadowRoot.pointerLockElement should be null.');

        document.exitPointerLock();
        test.done();
    });

    convertTemplatesToShadowRootsWithin(host);
    var host3 = host2.shadowRoot.querySelector('#host3');
    var host4 = host3.shadowRoot.querySelector('#host4');
    var host5 = host2.shadowRoot.querySelector('#host5');

    // All pointerLockElement should default to null.
    test.step(() => {
        assert_equals(document.pointerLockElement, null);
        assert_equals(host.shadowRoot.pointerLockElement, null);
        assert_equals(host2.shadowRoot.pointerLockElement, null);
        assert_equals(host3.shadowRoot.pointerLockElement, null);
        assert_equals(host4.shadowRoot.pointerLockElement, null);
        assert_equals(host5.shadowRoot.pointerLockElement, null);
    });

    var canvas = host3.shadowRoot.querySelector('canvas');
    await test_driver.bless('user gesture requests pointer lock', async () => {
      canvas.requestPointerLock();
    });
}, 'Test for pointerLockElement adjustment for Shadow DOM.');
</script>
